part of 'index.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({super.key, this.conversation, this.user});
  final EMConversation? conversation;
  final chat.UserInfo? user;

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => ChatProvider(context, widget.conversation, widget.user),
      child: Builder(
        builder: (context) {
          final provider = Provider.of<ChatProvider>(context);
          return GestureDetector(
            onTap: provider.pannelController.hide,
            child: Scaffold(
              backgroundColor: const Color(0xFFFAFAFA),
              appBar: AppBar(
                shadowColor: const Color(0xFF787878).withOpacity(0.02),
                elevation: 0.1,
                backgroundColor: Colors.white,
                surfaceTintColor: Colors.white,
                centerTitle: true,
                title: Column(
                  children: [
                    Text(
                      widget.user?.nickName?.isNotEmpty == true
                          ? widget.user!.nickName!
                          : 'user',
                      style: TextStyle(
                        fontSize: 18.w,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    if (ImManager.of.onlineUsers
                        .contains(widget.conversation?.id))
                      const Center(child: OnlineStatus(true)),
                  ],
                ),
              ),
              body: BuildMessageList<EMMessage, DateTime>(
                scrollController: provider._scrollController,
                refreshController: provider.refreshController,
                onLoading: provider.onLoading,
                sortedList: provider.messageList,
                groupBy: (value) {
                  return DateTime.fromMillisecondsSinceEpoch(value.serverTime);
                },
                groupRange: (left, right) =>
                    left.difference(right).inMinutes <= 10,
                groupHeaderBuilder: (value) => BuildMessageTime(
                  timestamp: value.serverTime,
                ),
                itemBuilder: (_, value) => BuildMessage(model: value),
              ),
              bottomNavigationBar: OperateBar(
                controller: provider.pannelController,
              ),
            ),
          );
        },
      ),
    );
  }
}
